<template>
    <!-- 添加客户 -->
    <div class="client-box">
        <el-dialog destroy-on-close :before-close="close" :title="addformInline.client_id?'修改客户':'新增客户'" :visible.sync="addDialogVisible" width="785px" :close-on-click-modal="false">
            <div class="add-client-box">
                <div class="add-client-title">必填信息</div>
                <el-form :show-close="false" :inline="true" :rules="rules" ref="ruleForm" :model="addformInline" class="demo-form-inline">
                    <el-form-item label="客户名称" prop="name">
                        <el-input maxlength="20" clearable class="input-width" v-model="addformInline.name" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="客户来源" prop="source">
                        <el-select filterable clearable class="input-width" v-model="addformInline.source" placeholder="">
                            <el-option v-for="(item,index) in clientSource" :key="index" :label="item.source_name" :value="item.source_name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="归属地区" prop="city">
                        <!-- , checkStrictly: true  -->
                        <el-cascader
                          placeholder=""
                          clearable
                          class="input-width"
                          v-model="addformInline.city"
                          :options="district"
                          :props="{ expandTrigger: 'hover', label: 'text'}"></el-cascader>
                    </el-form-item>
                    <el-form-item label="商务负责人" prop="wheelMan">
                        <el-select filterable clearable class="input-width" v-model="addformInline.wheelMan" placeholder="">
                            <el-option v-for="(item,index) in principal" :key="index" :label="item.nickname" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户等级" prop="grade">
                        <el-select clearable class="input-width" v-model="addformInline.grade" placeholder="">
                            <el-option v-for="(item,index) in clientLevel" :key="index" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
    
                    <el-form-item prop="contacts">
                        <div class="items-box" v-for="(item,index) in addformInline.contacts" :key="index">
                            <div class="items-box-item">
                                <p><span style="color: #F56C6C;font-size: 12px;margin-right: 3px;">*</span>联系人</p>
                                <el-input maxlength="20" clearable class="width" v-model="item.name" placeholder=""></el-input>
                            </div>
                            <div class="items-box-item">
                                <p>联系方式</p>
                                <!--  type="number" -->
                                <el-input 
                                type="number"
                                oninput="if(value.length>11)value=value.slice(0,11)"
                                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                                onfocus="this.removeAttribute('readonly');"
                                auto-complete="off"
                                 clearable class="width" v-model="item.phone" placeholder=""></el-input>
                            </div>
                            <div class="items-box-item">
                                <p>职务</p>
                                <el-input clearable class="width" v-model="item.job" placeholder=""></el-input>
                            </div>
                            <div class="items-box-item">
                                <span @click="addContacts(index)">{{index == 0 ? '添加' : '删除'}}</span>
                            </div>
                        </div>
                    </el-form-item>
    
                    <div class="add-client-title">选填信息</div>
                    <el-form-item label="法人">
                        <div class="input-box">
                            <el-input clearable class="width" v-model="addformInline.legalPerson" placeholder=""></el-input>
                            <div class="img-box" v-if="addformInline.fileFr.show">
                                <el-image :preview-src-list="[addformInline.fileFr.show]" @click.stop=""
                                    style="width: 35px; height: 35px;margin:0 3px;" :src="addformInline.fileFr.show"
                                    fit="cover"></el-image>
                            </div>
                            <el-upload class="upload-demo" accept=".png,.jpeg,.jpg" action="#" :show-file-list="false" :auto-upload="false"
                                :on-change="beforeUploadFr">
                                <span v-if="addformInline.fileFr.show" style="color: red;"
                                    @click.stop="delFile('fileFr')">删除</span>
                                <p v-if="!addformInline.fileFr.show">上传附件</p>
                            </el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item label="营业执照">
                        <div class="input-box">
                            <el-input clearable class="width" v-model="addformInline.license" placeholder=""></el-input>
                            <div class="img-box" v-if="addformInline.fileZz.show">
                                <el-image :preview-src-list="[addformInline.fileZz.show]" @click.stop=""
                                    style="width: 35px; height: 35px;margin:0 3px;" :src="addformInline.fileZz.show"
                                    fit="cover"></el-image>
                            </div>
                            <el-upload class="upload-demo" accept=".png,.jpeg,.jpg" action="#" :show-file-list="false" :auto-upload="false"
                                :on-change="beforeUploadZz">
                                <span v-if="addformInline.fileZz.show" style="color: red;"
                                    @click.stop="delFile('fileZz')">删除</span>
                                <p v-if="!addformInline.fileZz.show">上传附件</p>
                            </el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item label="注册资本">
                        <el-input maxlength="20" clearable class="input-width" v-model="addformInline.assets" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="客户地址">
                        <el-input maxlength="20" clearable class="input-width" v-model="addformInline.address" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="开户行">
                        <el-input maxlength="20" clearable class="input-width" v-model="addformInline.user" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="银行卡号">
                        <el-input maxlength="20" type="number" clearable class="input-width" v-model="addformInline.bank" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="其他">
                        <el-input show-word-limit maxlength="100" clearable :autosize="{minRows:4,maxRows:7}" style="width: 610px;" type="textarea"
                            v-model="addformInline.desc"></el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <div class="btn-box">
                            <el-button :loading="addLoading" type="primary" @click="addClient('ruleForm')">{{addformInline.client_id?'修改':'确认'}}</el-button>
                            <el-button @click="close">取消</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>
<script>

    export default {
        name: 'Dashboard',
        props: {
            formInline:{
                type:Object,
                default: ()=>{
                    return{
                        name: '',
                        source: '',
                        city: '',
                        wheelMan: '',
                        grade: '',
                        contacts: [{
                            name: '',
                            phone: '',
                            job: ''
                        }],
                        legalPerson: '',
                        license: '',
                        assets: '',
                        address: '',
                        user: '',
                        bank: '',
                        desc: '',
                        fileZz: {
                            show: '',
                            file: ''
                        },
                        fileFr: {
                            show: '',
                            file: ''
                        }
                    }
                },
                required:false
            },
            addDialogVisible: {
                type: Boolean,
                default: false,
                required: false,
            },
            clientSource:{
                type:Array,
                default:[],
                required: false,
            },
            clientLevel:{
                type:Array,
                default:[],
                required: false,
            },
            district:{
                type:Array,
                default:[],
                required: false,
            },
            principal:{
                type:Array,
                default:[],
                required: false,
            },
            addLoading:{
                type:Boolean,
                default:false,
                required: false,
            },
        },
        data() {
            var contacts = (rule, value, callback)=>{
                let arr = value;
                let num = 0;
                for(let i=0; i<arr.length; i++){
                if(arr[i].job==''||arr[i].name==''||arr[i].phone==''){
                    num+=1;
                }
                }
                if(num!=0){
                    callback(new Error('请填写完整联系人'));
                }else{
                    callback();
                }
            }
            return {
                rules: {
                    name: [
                        { required: true, message: '请输入客户名称', trigger: 'change' },
                        // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    source: [
                        { required: true, message: '请选择客户来源', trigger: 'change' }
                    ],
                    city:[
                        { required: true, message: '请选择归属地区', trigger: 'change' }
                    ],
                    wheelMan:[
                        { required: true, message: '请选择负责人', trigger: 'change' }
                    ],
                    grade:[
                        {required: true, message: '请选择客户等级', trigger: 'change'}
                    ],
                    // contacts:[
                    //     {validator: contacts, trigger: 'change'}
                    // ]
                },
                addformInline: {
                    name: '',
                    source: '',
                    city: '',
                    wheelMan: '',
                    grade: '',
                    contacts: [{
                        name: '',
                        phone: '',
                        job: ''
                    }],
                    legalPerson: '',
                    license: '',
                    assets: '',
                    address: '',
                    user: '',
                    bank: '',
                    desc: '',
                    fileZz: {
                        show: '',
                        file: ''
                    },
                    fileFr: {
                        show: '',
                        file: ''
                    }
                },
            }
        },
        watch:{
            addDialogVisible(val1,val2){
                let addformInline = this.addformInline;
                if(!this.addDialogVisible){

                }else{
                    console.log("清空",this.formInline)
                    addformInline = {
                        name: '',
                        source: '',
                        city: '',
                        wheelMan: '',
                        grade: '',
                        contacts: [{
                            name: '',
                            phone: '',
                            job: ''
                        }],
                        legalPerson: '',
                        license: '',
                        assets: '',
                        address: '',
                        user: '',
                        bank: '',
                        desc: '',
                        fileZz: {
                            show: '',
                            file: ''
                        },
                        fileFr: {
                            show: '',
                            file: ''
                        }
                    }
                    this.addformInline = addformInline;
                    if(this.$refs['ruleForm']){
                        this.$refs['ruleForm'].resetFields();
                    }
                    if(JSON.stringify(this.formInline) != '{}' && this.formInline.name){
                        console.log("有新数据")
                        this.addformInline = this.formInline;
                        console.log(this.addformInline)
                    }
                }
            }
        },
        computed: {

        },
        mounted() {

        },
        methods: {
            // 关闭弹窗
            close(){
                if(this.addLoading)return;
                if(this.$refs['ruleForm']){
                    this.$refs['ruleForm'].resetFields();
                }
                this.$emit('close', '');
            },
            // 添加联系人
            addContacts(index){
                console.log(index)
                let addformInline = this.addformInline;
                if(addformInline.contacts.length > 2 && index == 0){
                this.$message({
                    type:'warning',
                    message:'最多添加三个联系人'
                })
                return;
                }
                if(index == 0){
                addformInline.contacts.push({
                    name:'',
                    phone:'',
                    job:''
                })
                }else{
                addformInline.contacts.splice(index,1);
                }
                this.addformInline = addformInline;
            },
            // 选择文件(营业执照)
            beforeUploadZz(e){
                let addformInline = this.addformInline;
                if(10 < Number(e.size/1024/1024)){
                    this.$message('单文件大小不能超过10MB')
                    return;
                }
                this.reader(e.raw).then(res=>{
                    addformInline.fileZz = {
                        show:res,
                        file:e.raw
                    }
                })
                this.addformInline = addformInline;
            },
            // 选择文件(法人)
            beforeUploadFr(e){
                if(10 < Number(e.size/1024/1024)){
                    this.$message('单文件大小不能超过10MB')
                    return;
                }
                let addformInline = this.addformInline;
                this.reader(e.raw).then(res=>{
                addformInline.fileFr = {
                    show:res,
                    file:e.raw
                }
                })
                this.addformInline = addformInline;
            },
            // 文件转base64
            reader(file){
                return new Promise((resolve, reject)=>{
                    let reader = new FileReader()
                    reader.readAsDataURL(file) // 这里是最关键的一步，转换就在这里 （参数必须是blob对象）
                    reader.onloadend = function () {
                        // console.log(this.result)
                        resolve(this.result);
                    }
                })
            },
            // 新增客户
            addClient(formName){
                let addformInline = this.addformInline;
                // console.log("新增客户",addformInline)
                this.$refs[formName].validate((valid) => {
                if (valid) {
                    let arr = addformInline.contacts;
                    let num = 0;
                    for(let i=0; i<arr.length; i++){
                        if(arr[i].job==''||arr[i].name==''||arr[i].phone==''){
                            num+=1;
                        }
                    }
                    if(num != 0){
                        this.$message('请先填写完整联系人（姓名，电话，职务）');
                        return;
                    }
                    this.$emit('onSubmit',addformInline)
                } else {
                    console.log('error submit!!');
                    return false;
                }
                });
            },
            // 删除附件
            delFile(type){
                let addformInline = this.addformInline;
                switch(type){
                case 'fileFr':
                    addformInline.fileFr = {
                        show:'',
                        file:''
                    }
                    break;
                case 'fileZz':
                    addformInline.fileZz = {
                        show:'',
                        file:''
                    }
                    break;
                default:
                }
                this.addformInline = addformInline;
            },
        }

    }
</script>
<style lang="scss" scoped>
    @import './index.scss';
</style>